﻿using System;
using System.Collections;
using System.Collections.Generic;
using BehaviorDesigner.Runtime.Tasks.Basic.UnityGameObject;
using TMPro;
using UnityEngine;
using UnityEngine.UI;

public enum EntityType
{
    Player,
    Enemy
}

public class GameSession : MonoBehaviour
{
    private SceneLoader m_SceneLoader;
    
    public Sprite[] numberSprites;

    public int currentTurnCount = 0;
    
    public Dictionary<EntityType, int> entityTypeCountMap = new Dictionary<EntityType, int>();

    public WayPoint currentWayPoint;
    
    public void Awake()
    {
        if (FindObjectsOfType<GameSession>().Length == 1)
        {
            DontDestroyOnLoad(this.gameObject);
        }
        else
        {
            Destroy(this.gameObject);
        }
    }

    public void SetCurrentWayPoint(WayPoint wayPoint)
    {
        this.currentWayPoint = wayPoint;
    }
    
    private SceneLoader GetSceneLoader()
    {
        if (m_SceneLoader == null)
        {
            m_SceneLoader = GameObject.FindGameObjectWithTag(StaticDataManager.SCENE_LOADER_TAG)
                .GetComponent<SceneLoader>();
        }

        return m_SceneLoader;
    }
    public void StartGame()
    {
        SceneLoaderUtils.LoadSceneByIndex(1);
    }

    public void QuitGame()
    {
        #if UNITY_EDITOR
            UnityEditor.EditorApplication.isPlaying = false;
        #endif
        
        Application.Quit();
    }

//    public void EndPlayerTurn()
//    {
//        TurnManager.EndPlayerTurn();
//    }

    public ValueTuple<Sprite, Color> GetNumberSprite(int number)
    {
        Color color = Color.green;
        if (number <= 0)
        {
            color = Color.red;
        }

        number = Mathf.Abs(number);
        if (number > 9)
        {
            number = 9;
        }

        Sprite sprite = numberSprites[number];

        return new ValueTuple<Sprite, Color>(sprite, color);
    }

    public void FreshAllTileScore()
    {
        TileHelper.CalculateTileScore(GameObject.FindGameObjectWithTag(StaticDataManager.PLAYER_TAG));
        foreach (GameObject tileObject in GameObject.FindGameObjectsWithTag(StaticDataManager.TILE_TAG))
        {
            tileObject.GetComponent<TileMonoBehaviour>().FreshScoreNumberSprite();
        }
    }
    
    public void InitialHpBar(GameObject hpBar)
    {
        // 填满就是了
        hpBar.GetComponent<Image>().fillAmount = 1;
    }

    public void FlushHpBar(int currentHp, int maxHp, GameObject hpBar)
    {

        // 其实隐藏可能会更好一点 不过还是先不管了
        if (currentHp != maxHp)
        {
            float fillAmount = currentHp * 1f / maxHp;

            hpBar.GetComponent<Image>().fillAmount = fillAmount;
        }
    }

    public void FlushHpText(TextMeshProUGUI hpText, int currentHp)
    {
        hpText.SetText(currentHp.ToString());   
    }

    public void FlushShieldText(TextMeshProUGUI shieldText, Image shieldImage, int currentShield)
    {
        bool isDisplayIcon = currentShield != 0;
        
        shieldText.gameObject.SetActive(isDisplayIcon);
        shieldImage.gameObject.SetActive(isDisplayIcon);

        shieldText.SetText(currentShield.ToString());
    }

    public void BattleStart()
    {
        entityTypeCountMap.Clear();
        entityTypeCountMap[EntityType.Enemy] = 0;
        entityTypeCountMap[EntityType.Player] = 0;
    }

    public void AddEntity(EntityType entityType)
    {
        if (!entityTypeCountMap.ContainsKey(entityType))
        {
            entityTypeCountMap.Add(entityType, 0);
        }
        
        entityTypeCountMap[entityType] += 1;
    }
    
    public void EntityDeath(EntityType entityType)
    {
        entityTypeCountMap[entityType] -= 1;

        Debug.Log($"实体 {entityType.ToString()} 被摧毁, 当前剩余 玩家: {entityTypeCountMap[EntityType.Player]}, 敌人: {entityTypeCountMap[EntityType.Enemy]}");
        
        CheckBattleStatus();
    }

    public void CheckBattleStatus()
    {
        Debug.Log("有实体消失了，检查一下当前的战斗状态");
        if (entityTypeCountMap[EntityType.Enemy] == 0)
        {
            Debug.Log("玩家胜利");
            BattleFinish(true, true);
        }
        else if (entityTypeCountMap[EntityType.Player] == 0)
        {
            Debug.Log("玩家失败");
            BattleFinish(false, true);
        }
    }

    public void BattleFinish(bool isWin, bool isNeedBackMapScene)
    {
        // TODO 根据当前的场景判断当前状态是胜利还是失败
        // TODO 胜利的话 根据 {未定义} 从卡堆中抽出3张卡
        // TODO 失败的话就游戏结束，直接跳统计动画
        if (isWin)
        {
            GameObject.FindGameObjectWithTag(StaticDataManager.UI_MANAGER_TAG).GetComponent<UIManager>().DisplayRewardListPanel(isNeedBackMapScene);
            // TODO 怎么做到在结束后就返回地图界面呢
        }
    }

    public void BackToMapScene()
    {
        GetSceneLoader().LoadRouteScene();
    }
}